package com.ctcc.controller;

import com.alibaba.fastjson.JSONObject;
import com.ctcc.entity.TeamAccessToken;
import com.ctcc.serviceImpl.DepartmentImpl;
import com.ctcc.serviceImpl.EmployeeImpl;
import com.ctcc.serviceImpl.FormDataImpl;
import com.ctcc.serviceImpl.FormInfoService;
import com.ctcc.util.AESEncryptor;
import com.ctcc.util.AccessTokenService;
import com.ctcc.util.Const;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.JsonNode;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;


/**
 * Created by Peanut on 2018/1/29.
 */
@RestController
public class CloudFormController {
    private AccessTokenService accessTokenService;
    private DepartmentImpl departmentImpl;
    private EmployeeImpl employeeImpl;
    private FormDataImpl formDataImpl;
    private FormInfoService formInfoService;
    @Autowired
    public CloudFormController(AccessTokenService accessTokenService, DepartmentImpl departmentImpl, EmployeeImpl employeeImpl, FormDataImpl formDataImpl, FormInfoService formInfoService) {
        this.accessTokenService = accessTokenService;
        this.departmentImpl = departmentImpl;
        this.employeeImpl = employeeImpl;
        this.formDataImpl = formDataImpl;
        this.formInfoService = formInfoService;
    }
    @Value("${cloudhub.eid}")
    private String eid;
    @Value("${cloudhub.aesKey}")
    private String aesKey;

    //@Scheduled(fixedRate = 5000)
    @GetMapping(value = "/getall")
    /**
     *获取组织数据
     */
    public void getAllDept() throws Exception {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("eid", eid);
        JsonNode jsonNode = new JsonNode(jsonObj.toString());
        departmentImpl.getAllDept(Const.yun_org_getall_url, jsonNode);

    }

    /**
     * 得到token
     */
    @GetMapping(value = "/gettoken")
    public void getAllFormData() {
        TeamAccessToken a = accessTokenService.getTeamAccessToken();
        System.out.print(a.getAccessToken());
    }

    /**
     * 获取所有组织人员
     *
     * @throws Exception
     */
    @GetMapping(value = "/getallempl")
    public void getAllEmple() throws Exception {
        //清空临时表
        employeeImpl.removeEmplTemp();
        //将获取到的数据分页放入临时表
        JSONObject jsonObj = new JSONObject();
        int begin = 0;
        int count = 1000;
        jsonObj.put("eid", eid);
        jsonObj.put("begin", begin);
        jsonObj.put("count", count);
        JsonNode jsonNode = new JsonNode(jsonObj.toString());
        int page = employeeImpl.getAllEmpl(Const.yun_org_getpersonall_url, jsonNode);
        while (page > count) {
            begin = count++;
            jsonObj.put("begin", begin);
            jsonObj.put("count", count);
            page = employeeImpl.getAllEmpl(Const.yun_org_getpersonall_url, jsonNode);
        }
        //将数据放入表中
        employeeImpl.saveAlltoEmpl();


    }

    /**
     * 获取表单提交的数据
     */
    @GetMapping(value = "/getformdata")
    public String getFormDate() throws Exception {
        JSONObject jsonObj = new JSONObject();
        TeamAccessToken teamAccessToken = accessTokenService.getTeamAccessToken();
        jsonObj.put("formCodeId", Const.formCodeIdtest);
        //jsonObj.put("accessToken",teamAccessToken.getAccessToken());
        JsonNode jsonNode = new JsonNode(jsonObj.toString());
        String result = formDataImpl.getAllFormData(teamAccessToken.getAccessToken(), Const.yun_org_getworkflow_url, jsonNode);
        return result;
    }

    /**
     * 以开发者形式获取表单提交数据
     *
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/getdata")
    public String getForm(@RequestBody String requestBody,
                          HttpServletRequest request) throws Exception {
        //开发者key
        System.out.println(request.getContentType());
        AESEncryptor encryptor = new AESEncryptor(aesKey);
        //得到的requestBody密文参数
        //String requestBody = "这里是接收到的推送内容(密文)";
        String json = encryptor.decrypt(requestBody);
        System.out.println(json);
        return "success";
    }



    /**
     *
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/webhook")
    public String getForm2(@RequestBody String response) {
        try {
            formInfoService.handleWebHook(response);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
/*
测试代码
 */
    @GetMapping("/parsejson")
    public HttpEntity testParseJson(ObjectMapper objectMapper) {
        try {
            File file = Paths.get(this.getClass().getClassLoader().getResource("data2.json").toURI()).toFile();
            String data = IOUtils.toString(new FileInputStream(file));
            return ResponseEntity.ok(formInfoService.handleWebHook(data));
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
}
